<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
<meta name="viewport"
      content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">

    <meta name="author" content="kissdata">


    <meta name="subtitle" content="人生笔记">


    <meta name="description" content="南邮计算机学院2021毕业生王鹏的介绍，cs软件工程专业">


    <meta name="keywords" content="wangpeng 王鹏 南邮 南京">


<title>C 可变长参数的应用 | 王鹏的小岛</title>



    <link rel="icon" href="/myIcon.ico">




    <!-- stylesheets list from _config.yml -->
    
    <link rel="stylesheet" href="/css/style.css">
    



    <!-- scripts list from _config.yml -->
    
    <script src="/js/script.js"></script>
    
    <script src="/js/tocbot.min.js"></script>
    



    
    
        <!-- MathJax配置，可通过单美元符号书写行内公式等 -->
<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
    "HTML-CSS": {
        preferredFont: "TeX",
        availableFonts: ["STIX","TeX"],
        linebreaks: { automatic:true },
        EqnChunk: (MathJax.Hub.Browser.isMobile ? 10 : 50)
    },
    tex2jax: {
        inlineMath: [ ["$", "$"], ["\\(","\\)"] ],
        processEscapes: true,
        ignoreClass: "tex2jax_ignore|dno",
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    },
    TeX: {
        equationNumbers: { autoNumber: "AMS" },
        noUndefined: { attributes: { mathcolor: "red", mathbackground: "#FFEEEE", mathsize: "90%" } },
        Macros: { href: "{}" }
    },
    messageStyle: "none"
    });
</script>
<!-- 给MathJax元素添加has-jax class -->
<script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for(i=0; i < all.length; i += 1) {
            all[i].SourceElement().parentNode.className += ' has-jax';
        }
    });
</script>
<!-- 通过连接CDN加载MathJax的js代码 -->
<script type="text/javascript" async
        src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML">
</script>


    


<meta name="generator" content="Hexo 7.0.0"></head>

<body>
    <script>
        // this function is used to check current theme before page loaded.
        (() => {
            const currentTheme = window.localStorage && window.localStorage.getItem('theme') || '';
            const isDark = currentTheme === 'dark';
            const pagebody = document.getElementsByTagName('body')[0]
            if (isDark) {
                pagebody.classList.add('dark-theme');
                // mobile
                document.getElementById("mobile-toggle-theme").innerText = "· Dark"
            } else {
                pagebody.classList.remove('dark-theme');
                // mobile
                document.getElementById("mobile-toggle-theme").innerText = "· Light"
            }
        })();
    </script>

    <div class="wrapper">
        <header>
    <nav class="navbar">
        <div class="container">
            <div class="navbar-header header-logo"><a href="/">侠之大者</a></div>
            <div class="menu navbar-right">
                
                    <a class="menu-item" href="/update/mystate">Career</a>
                
                    <a class="menu-item" href="/category">Legend</a>
                
                    <a class="menu-item" href="/about">Me</a>
                
                <input id="switch_default" type="checkbox" class="switch_default">
                <label for="switch_default" class="toggleBtn"></label>
            </div>
        </div>
    </nav>

    
    <nav class="navbar-mobile" id="nav-mobile">
        <div class="container">
            <div class="navbar-header">
                <div>
                    <a href="/">侠之大者</a><a id="mobile-toggle-theme">·&nbsp;Light</a>
                </div>
                <div class="menu-toggle" onclick="mobileBtn()">&#9776; Menu</div>
            </div>
            <div class="menu" id="mobile-menu">
                
                    <a class="menu-item" href="/update/mystate">Career</a>
                
                    <a class="menu-item" href="/category">Legend</a>
                
                    <a class="menu-item" href="/about">Me</a>
                
            </div>
        </div>
    </nav>

</header>
<script>
    var mobileBtn = function f() {
        var toggleMenu = document.getElementsByClassName("menu-toggle")[0];
        var mobileMenu = document.getElementById("mobile-menu");
        if(toggleMenu.classList.contains("active")){
           toggleMenu.classList.remove("active")
            mobileMenu.classList.remove("active")
        }else{
            toggleMenu.classList.add("active")
            mobileMenu.classList.add("active")
        }
    }
</script>
            <div class="main">
                <div class="container">
    
    
        <div class="post-toc">
    <div class="tocbot-list">
    </div>
    <div class="tocbot-list-menu">
        <a class="tocbot-toc-expand" onclick="expand_toc()">Expand all</a>
        <a onclick="go_top()">Back to top</a>
        <a onclick="go_bottom()">Go to bottom</a>
    </div>
</div>

<script>
    var tocbot_timer;
    var DEPTH_MAX = 6; // 为 6 时展开所有
    var tocbot_default_config = {
        tocSelector: '.tocbot-list',
        contentSelector: '.post-content',
        headingSelector: 'h1, h2, h3, h4, h5',
        orderedList: false,
        scrollSmooth: true,
        onClick: extend_click,
    };

    function extend_click() {
        clearTimeout(tocbot_timer);
        tocbot_timer = setTimeout(function() {
            tocbot.refresh(obj_merge(tocbot_default_config, {
                hasInnerContainers: true
            }));
        }, 420); // 这个值是由 tocbot 源码里定义的 scrollSmoothDuration 得来的
    }

    document.ready(function() {
        tocbot.init(obj_merge(tocbot_default_config, {
            collapseDepth: 1
        }));
    });

    function expand_toc() {
        var b = document.querySelector('.tocbot-toc-expand');
        var expanded = b.getAttribute('data-expanded');
        expanded ? b.removeAttribute('data-expanded') : b.setAttribute('data-expanded', true);
        tocbot.refresh(obj_merge(tocbot_default_config, {
            collapseDepth: expanded ? 1 : DEPTH_MAX
        }));
        b.innerText = expanded ? 'Expand all' : 'Collapse all';
    }

    function go_top() {
        window.scrollTo(0, 0);
    }

    function go_bottom() {
        window.scrollTo(0, document.body.scrollHeight);
    }

    function obj_merge(target, source) {
        for (var item in source) {
            if (source.hasOwnProperty(item)) {
                target[item] = source[item];
            }
        }
        return target;
    }
</script>
    

    
    <article class="post-wrap">
        <header class="post-header">
            <h1 class="post-title">C 可变长参数的应用</h1>
            
                <div class="post-meta">
                    
                        Author: <a itemprop="author" rel="author" href="/">kissdata</a>
                    

                    
                        <span class="post-time">
                        Date: <a href="#">Oct 30, 2023&nbsp;&nbsp;0:00</a>
                        </span>
                    
                    
                        <span class="post-category">
                    Category:
                            
                                <a href="/categories/Review/">Review</a>
                            
                        </span>
                    
                </div>
            
        </header>

        <div class="post-content">
            <h3 id="特殊"><a href="#特殊" class="headerlink" title="特殊"></a>特殊</h3><p>打印三角形时，可以看作按行处理。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">PrintHorLineUseChar(<span class="string">&#x27; &#x27;</span>, <span class="number">3</span>, <span class="string">&#x27;*&#x27;</span>, <span class="number">2</span>);   <span class="comment">// 3个空 + 2个*</span></span><br><span class="line">PrintHorLineUseChar(<span class="string">&#x27; &#x27;</span>, <span class="number">2</span>, <span class="string">&#x27;*&#x27;</span>, <span class="number">4</span>);</span><br><span class="line">PrintHorLineUseChar(<span class="string">&#x27; &#x27;</span>, <span class="number">1</span>, <span class="string">&#x27;*&#x27;</span>, <span class="number">5</span>); </span><br></pre></td></tr></table></figure>

<p>这个实现容易，两个for循环移入到子函数就行。其实把 print 再包装了一层，看起来更通俗简洁了。</p>
<p>如果希望它传入的是多个呢？</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// call</span></span><br><span class="line">PrintHorLineUseChar(<span class="string">&#x27;x&#x27;</span>, <span class="number">15</span>);               <span class="comment">// 1种, 15个 x</span></span><br><span class="line">PrintHorLineUseChar(<span class="string">&#x27;#&#x27;</span>, <span class="number">6</span>, <span class="string">&#x27;*&#x27;</span>, <span class="number">8</span>);        <span class="comment">// 2种, 6个# + 8个*</span></span><br><span class="line">PrintHorLineUseChar(<span class="string">&#x27;#&#x27;</span>, <span class="number">3</span>, <span class="string">&#x27; &#x27;</span>, <span class="number">4</span>, <span class="string">&#x27;*&#x27;</span>, <span class="number">5</span>);</span><br></pre></td></tr></table></figure>

<p>这种在 C++ 里有函数重载，但是也只能处理有限情况，我是希望它更一般一些。C 语言有 <code>可变长参数</code> ，也许能解决问题，当然必须提供一个确定的参数数量</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// call</span></span><br><span class="line">PrintHorLineUseChar(<span class="number">1</span>, <span class="string">&#x27;x&#x27;</span>, <span class="number">15</span>);             <span class="comment">// 1种, 15个 x</span></span><br><span class="line">PrintHorLineUseChar(<span class="number">2</span>, <span class="string">&#x27;#&#x27;</span>, <span class="number">6</span>, <span class="string">&#x27;*&#x27;</span>, <span class="number">8</span>);      <span class="comment">// 2种, 6个# + 8个*</span></span><br><span class="line">PrintHorLineUseChar(<span class="number">3</span>, <span class="string">&#x27;#&#x27;</span>, <span class="number">3</span>, <span class="string">&#x27; &#x27;</span>, <span class="number">4</span>, <span class="string">&#x27;*&#x27;</span>, <span class="number">5</span>);</span><br></pre></td></tr></table></figure>

<p>这个时候函数声明就难了，因为类型不一样，起码需要两个 <code>...</code> ，一个控制字符，一个统计数量。<code>void f(int, ..., ...);</code>很明显不行。（当然后续用结构体把这两种类型包装一下，就容易了）。</p>
<h2 id="一般"><a href="#一般" class="headerlink" title="一般"></a>一般</h2><p>因为打印一个行，那么字符图形有先后，等于是有序的（不是大小角度）。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// call</span></span><br><span class="line">UI[] = &#123;<span class="string">&#x27;x&#x27;</span>&#125;;</span><br><span class="line">PrintHorLineUseChar(<span class="number">1</span>, <span class="number">15</span>);    <span class="comment">// 1种, 15个 x</span></span><br><span class="line">UI[] = &#123;<span class="string">&#x27;#&#x27;</span>, <span class="string">&#x27;*&#x27;</span>&#125;</span><br><span class="line">PrintHorLineUseChar(<span class="number">2</span>, <span class="number">6</span>, <span class="number">8</span>);  <span class="comment">// 2种, 6个# + 8个*</span></span><br><span class="line">UI[] = &#123;<span class="string">&#x27;#&#x27;</span>, <span class="string">&#x27; &#x27;</span>, <span class="string">&#x27;*&#x27;</span>&#125;;</span><br><span class="line">PrintHorLineUseChar(<span class="number">3</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>);</span><br></pre></td></tr></table></figure>

<p>实现方法。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdarg.h&gt;</span></span></span><br><span class="line"><span class="type">char</span> UI[<span class="number">8</span>] = &#123;<span class="string">&#x27; &#x27;</span>, <span class="string">&#x27;*&#x27;</span>, <span class="string">&#x27;#&#x27;</span>&#125;;</span><br><span class="line"><span class="comment">/** </span></span><br><span class="line"><span class="comment"> *  功能： 显示有限种字符组成的横线</span></span><br><span class="line"><span class="comment"> *  参数： kind 几种不同字符</span></span><br><span class="line"><span class="comment"> *        </span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="type">void</span> <span class="title function_">PrintHorLineUseChar</span><span class="params">(<span class="type">int</span> kind, ...)</span> &#123;</span><br><span class="line">  va_list valist;</span><br><span class="line">  va_start(valist, kind);</span><br><span class="line">  <span class="keyword">for</span> (<span class="type">int</span> k = <span class="number">0</span>; k &lt; kind; ++k) &#123;</span><br><span class="line">    <span class="type">int</span> tmpCount = va_arg(valist, <span class="type">int</span>);</span><br><span class="line">    <span class="keyword">for</span> (<span class="type">int</span> i = <span class="number">0</span>; i &lt; tmpCount; ++i) &#123;</span><br><span class="line">      <span class="built_in">putchar</span>(UI[k]);</span><br><span class="line">    &#125;;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//call</span></span><br><span class="line">UI[<span class="number">0</span>] = <span class="string">&#x27;x&#x27;</span>;</span><br><span class="line">PrintHorLineUseChar(<span class="number">1</span>, <span class="number">15</span>);</span><br><span class="line">UI[<span class="number">0</span>] = <span class="string">&#x27;#&#x27;</span>, UI[<span class="number">1</span>] = <span class="string">&#x27;*&#x27;</span>;</span><br><span class="line">PrintHorLineUseChar(<span class="number">2</span>, <span class="number">6</span>, <span class="number">8</span>);</span><br><span class="line">UI[<span class="number">2</span>] = <span class="string">&#x27;*&#x27;</span>, UI[<span class="number">1</span>] = <span class="string">&#x27; &#x27;</span>;</span><br><span class="line">PrintHorLineUseChar(<span class="number">3</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>);</span><br></pre></td></tr></table></figure>

<p>唯一的缺点是 UI 上限是固定的，但是 <code>char</code> 类型数组占空间不大，提供一个大点的数就行了。</p>
<h3 id="测试"><a href="#测试" class="headerlink" title="测试"></a>测试</h3><p>这个用来打印三角形就方便的多，已等边三角形为例。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdarg.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">const</span> <span class="type">char</span> UI[] = &#123;<span class="string">&#x27; &#x27;</span>, <span class="string">&#x27;*&#x27;</span>&#125;;</span><br><span class="line"><span class="type">void</span> <span class="title function_">PrintHxx</span><span class="params">(<span class="type">int</span> kind, ...)</span>;</span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span>, <span class="type">char</span> **)</span> &#123;</span><br><span class="line">  <span class="type">int</span> lines = <span class="number">0</span>;</span><br><span class="line">  <span class="built_in">scanf</span>(<span class="string">&quot;%d&quot;</span>, &amp;lines);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (<span class="type">int</span> i = <span class="number">0</span>; i &lt; lines; ++i) &#123;</span><br><span class="line">    PrintHxx(<span class="number">2</span>, lines - <span class="number">1</span> - i, <span class="number">2</span> * i + <span class="number">1</span>); <span class="comment">// 先空后星</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (i &lt; lines - <span class="number">1</span>) <span class="built_in">printf</span>(<span class="string">&quot;\n&quot;</span>);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


        </div>

        
            <section class="post-copyright">
                
                
                
                
                     <p class="copyright-item">
                         <span>Slogan:</span>
                         <span>人生三大错觉：我躲得过去，我能反杀，是不是<strong>喜欢我?</strong></span>
                     </p>
                

            </section>
        
        <section class="post-tags">
            <div>
            </div>
            <div>
                <a href="javascript:window.history.back();">back</a>
                <span>· </span>
                <a href="/">home</a>
            </div>
        </section>
        <section class="post-nav">
            
                <a class="prev" rel="prev" href="/2023/11-4/deploy_gocv/">🆗 | Centos7 安装openCV4</a>
            
            
            <a class="next" rel="next" href="/2023/10-17/howstart_go/">Go 起步</a>
            
        </section>


    </article>
</div>

            </div>
            <footer id="footer" class="footer">
    <div class="copyright">
        <span>187-9597-5517 &nbsp; 王鹏 @ <a href="https://cs.njupt.edu.cn/" target="_blank">njupt</a</span>
    </div>
</footer>

    </div>
</body>

</html>